package com.cxs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxs.entity.dto.ReservationSeatDTO;
import com.cxs.enums.ReservationMarkEnums;
import com.cxs.mapper.ClassroomMapper;
import com.cxs.mapper.ClazzMapper;
import com.cxs.mapper.SeatOrderMapper;
import com.cxs.mapper.StudentMapper;
import com.cxs.entity.Classroom;
import com.cxs.entity.Seat;
import com.cxs.entity.SeatOrder;
import com.cxs.entity.Student;
import com.cxs.service.SeatService;
import com.cxs.mapper.SeatMapper;
import com.cxs.entity.bo.ClazzBo;
import com.cxs.entity.bo.SeatBo;
import com.cxs.entity.vo.ReservationMarkVO;
import com.cxs.entity.vo.Result;
import com.cxs.entity.vo.SeatOrderDetailVO;
import com.cxs.entity.vo.SeatOrderInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName: SeatServiceImpl
 * @description:
 * @author: 诗涵
 * @create: 2024-01-07 08:17
 */
@Service
public class SeatServiceImpl extends ServiceImpl<SeatMapper, Seat>
    implements SeatService{

    @Autowired
    private SeatMapper seatMapper;

    @Autowired
    private ClassroomMapper classroomMapper;

    @Autowired
    private SeatOrderMapper seatOrderMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public List<SeatOrderInfoVO> getSeatListInfo(Integer id, LocalDate date) {

        List<SeatOrderInfoVO> childList = new ArrayList<>();

        SeatBo bo = seatMapper.selectOrderInfoBySeatId(id, date);
        if (null == bo) {
            Seat seat = seatMapper.selectById(id);
            bo = new SeatBo();
            BeanUtils.copyProperties(seat, bo);
        }
        Classroom classroom = classroomMapper.selectById(bo.getClassroomId());
        int start = classroom.getOpenTimeStart().getHour();
        int end = classroom.getOpenTimeEnd().getHour();
        List<SeatOrder> orderList = bo.getOrderList();
        Map<String,SeatOrder> orderMap =  CollectionUtils.isEmpty(orderList) ? new HashMap<>() : orderList.stream().collect(Collectors.toMap(SeatOrder::getReservationMark, Function.identity(), (o1, o2) -> o1));
        List<ReservationMarkVO> reservationMarkVOList = ReservationMarkEnums.getReservationMarkVOList(start, end);
        for (ReservationMarkVO reservationMarkVO : reservationMarkVOList) {
            SeatOrderInfoVO v = new SeatOrderInfoVO();
            v.setSeatId(bo.getId());
            v.setReservationMark(reservationMarkVO.getMark());
            v.setTimeRange(reservationMarkVO.getTimeRange());
            v.setSno(bo.getSeatNo());
            SeatOrder seatOrder = orderMap.get(reservationMarkVO.getMark());
            if (null != seatOrder) {
                v.setCreateTime(seatOrder.getCreateTime());
                v.setFlag(Boolean.TRUE);
                v.setId(seatOrder.getId());
            } else {
                v.setFlag(Boolean.FALSE);
            }
            childList.add(v);
        }
        return childList;
    }

    @Override
    public void getSeatOrderInfo(Integer id, Result r) {
        if (null == id) {
            r.setCode(-1);
            r.setMsg("id不能为空");
            return;
        }

        SeatOrder seatOrder = seatOrderMapper.selectById(id);

        if (null == seatOrder) {
            r.setCode(-1);
            r.setMsg("预定不存在");
            return;
        }

        Seat seat = seatMapper.selectById(seatOrder.getSeatId());
        if (null == seat) {
            r.setCode(-1);
            r.setMsg("座位不存在");
            return;
        }
        Classroom classroom = classroomMapper.selectById(seat.getClassroomId());
        if (null == classroom) {
            r.setCode(-1);
            r.setMsg("自习室不存在");
            return;
        }
        Student student = studentMapper.selectById(seatOrder.getSno());

        ClazzBo info = clazzMapper.getClazzInfoByClazzId(student.getClazzId());

        List<ReservationMarkVO> reservationMarkVOList = ReservationMarkEnums.getReservationMarkVOList(classroom.getOpenTimeStart().getHour(), classroom.getOpenTimeEnd().getHour());
        Map<String, ReservationMarkVO> map = CollectionUtils.isEmpty(reservationMarkVOList) ? new HashMap<>() : reservationMarkVOList.stream().collect(Collectors.toMap(ReservationMarkVO::getMark, Function.identity(), (o1, o2) -> o1));
        SeatOrderDetailVO vo = new SeatOrderDetailVO();
        BeanUtils.copyProperties(seatOrder, vo);
        vo.setName(student.getName());
        vo.setPhone(student.getPhone());
        vo.setSex(student.getSex());
        ReservationMarkVO reservationMarkVO = map.get(seatOrder.getReservationMark());
        if (null != reservationMarkVO) {
            vo.setTimeRange(reservationMarkVO.getTimeRange());
        }
        vo.setCollageName(info.getGradeName());
        vo.setClazzName(info.getClazzName());

        r.setData(vo);
    }

    @Override
    public void reservationSeat(ReservationSeatDTO dto, Integer sno, Result r) {
        LocalDate date = dto.getDate();
        LocalDate now = LocalDate.now();
        if (date.isBefore(now)) {
            r.setCode(-1);
            r.setMsg("该时间不可预约座位");
            return;
        }
        if (Duration.between(LocalDateTime.of(now, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MIN)).toDays() > 7L) {
            r.setCode(-1);
            r.setMsg("仅支持预定一周内的座位");
            return;
        }
        LambdaQueryWrapper<SeatOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SeatOrder::getReservationMark, dto.getMark())
                .eq(SeatOrder::getDate, dto.getDate())
                .eq(SeatOrder::getSno, sno);
        List<SeatOrder> seatOrders = seatOrderMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(seatOrders)) {
            r.setCode(-1);
            r.setMsg("预定失败,该时间段内您已进行预定座位,请按时去学习,把座位留给需要的同学,谢谢!");
            return;
        }
        Seat seat = seatMapper.selectById(dto.getSeatId());
        if (null == seat) {
            r.setCode(-1);
            r.setMsg("座位不存在");
            return;
        }
        Classroom classroom = classroomMapper.selectById(seat.getClassroomId());
        if (null == classroom) {
            r.setCode(-1);
            r.setMsg("自习室不存在");
            return;
        }

        Integer openType = classroom.getOpenType();
        // 0每天开放，1工作日开放2休息日开放
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        if (openType == 0) {
        } else if (openType == 1) {
            if (dayOfWeek.equals(DayOfWeek.SATURDAY) || dayOfWeek.equals(DayOfWeek.SUNDAY)) {
                r.setCode(-1);
                r.setMsg(classroom.getName() + "自习室" + "仅工作日可定");
                return;
            }
        } else if (openType == 2) {
            if (!dayOfWeek.equals(DayOfWeek.SATURDAY) && !dayOfWeek.equals(DayOfWeek.SUNDAY)) {
                r.setCode(-1);
                r.setMsg(classroom.getName() + "自习室" + "仅休息日可定");
                return;
            }
        } else {
            r.setCode(-1);
            r.setMsg("自习室开放时间有误");
            return;
        }

        List<ReservationMarkVO> reservationMarkVOList = ReservationMarkEnums.getReservationMarkVOList(classroom.getOpenTimeStart().getHour(), classroom.getOpenTimeEnd().getHour());
        Map<String, ReservationMarkVO> map = CollectionUtils.isEmpty(reservationMarkVOList) ? new HashMap<>() : reservationMarkVOList.stream().collect(Collectors.toMap(ReservationMarkVO::getMark, Function.identity(), (o1, o2) -> o1));

        SeatOrder order = new SeatOrder();
        order.setSeatId(dto.getSeatId());
        order.setCreateTime(LocalDateTime.now());
        order.setDate(dto.getDate());
        ReservationMarkVO reservationMarkVO = map.get(dto.getMark());
        if (reservationMarkVO == null) {
            r.setCode(-1);
            r.setMsg("预约时间有误");
            return;
        }
        int hour = LocalDateTime.now().getHour();
        if (date.equals(now)) {
            if (reservationMarkVO.getStartTime() < hour) {
                r.setCode(-1);
                r.setMsg("当前时间不可预订,请选择其他时间预定");
                return;
            }
        }
        order.setReservationMark(dto.getMark());
        order.setStartTime(reservationMarkVO.getStartTime());
        order.setEndTime(reservationMarkVO.getEndTime());
        order.setSno(sno);
        int insert = seatOrderMapper.insert(order);
        if (insert != 1) {
            r.setCode(-1);
            r.setMsg("预约失败");
            return;
        }
    }
}




